package com.trg.flex
{
	import com.trg.flex.dt.DataTable;
	import com.trg.flex.frm.FormContainer;
	import com.trg.flex.frm.FormEvent;
	import com.trg.flex.messages.ErrorMessageConvertor;
	
	import mx.controls.Alert;
	
	/**
	 * Same idea as <code>EntityActionHelper</code> except that it goes through a <code>ModelCache</code>.
	 * 
	 * @see EntityActionHelper
	 * @see ModelCache
	 */
	public class CacheActionHelper
	{
		public var cache:ModelCache;

		protected var _form:FormContainer;
		
		protected var errorMessageConvertor:ErrorMessageConvertor = ErrorMessageConvertor.getInstance();
		
		[Bindable]
		public function get form():FormContainer {
			return _form;
		}
		public function set form(value:FormContainer):void {
			if (_form != null) {
				_form.removeEventListener(FormEvent.COMMIT, commitHandler);	
				_form.removeEventListener(FormEvent.COMMIT_COMPLETE, commitCompleteHandler);
			}
			_form = value;
			if (_form != null) {
				_form.addEventListener(FormEvent.COMMIT, commitHandler);	
				_form.addEventListener(FormEvent.COMMIT_COMPLETE, commitCompleteHandler);
			}
		}
		
		[Bindable]
		public var table:DataTable;
		
		[Bindable]
		public var confirmDelete:Boolean = true;

		public function deleteSelected():void {
			if (table == null) return;
			deleteItems(table.selectedItems);
		}
		
		public function deleteItems(items:*):void {
			if(items == null || (items is Array && items.length == 0)) return;
			if (!(items is Array)) {
				items = [items];
			}
			var msg:String = items.length > 1 ? "Delete these items?" : "Delete this item?"
			FlexUtils.confirm(msg ,"DELETE", Alert.YES | Alert.NO, null, deleteConfirmCallback, items);
		}
		
		public function deleteConfirmCallback(result:*, items:Array):void {
			if (result == Alert.YES) {
				cache.deleteList(items, new Callback(deleteCompleteHandler, deleteFailureHandler));
			}
		}
		
		public function deleteCompleteHandler(result:*=null):void {
			if (table != null) table.refresh();
		}
		
		public function deleteFailureHandler(fault:Error):void {
			Alert.show("Item(s) could not be deleted. " + errorMessageConvertor.getMessage(fault).text, "ERROR");
		}
		
		public function commitHandler(event:FormEvent):void {
			if (event.original == null)
				cache.create(event.formBean, event.callback);
			else
				cache.update(event.formBean, event.callback);
		}
		
		public function commitCompleteHandler(event:FormEvent):void {
			//if (table != null) table.refresh();
		}
	}
}